package com.lianqi.emcpframework.ddd.gencode.updater;

import java.lang.annotation.Annotation;

import javax.lang.model.element.TypeElement;

import org.apache.commons.lang3.StringUtils;

import com.lianqi.emcpframework.ddd.gencode.EnableGenForAggregate;
import com.lianqi.emcpframework.ddd.gencode.EnableGenForEntity;

import lombok.AccessLevel;
import lombok.Getter;

@Getter(AccessLevel.PUBLIC)
public class GenUpdaterParser {
    private final TypeElement typeElement;

    private String packageName;
    private String className;
    private String parentClassName;

    public GenUpdaterParser(TypeElement typeElement) {
        this.typeElement = typeElement;
    }

    public void read(Annotation annotation) {
        if (annotation instanceof GenUpdater) {
            readFromGenUpdate((GenUpdater)annotation);
        }
        if (annotation instanceof EnableGenForAggregate) {
            readFromEnableGenForAggregate((EnableGenForAggregate)annotation);
        }
        if (annotation instanceof EnableGenForEntity) {
            readFromEnableGenForEntity((EnableGenForEntity)annotation);
        }

    }

    /**
     * 生成updater name
     * 
     * @param userDriect
     * @return
     */
    String buildClassName(boolean userDriect) {

        if (userDriect) {
            return typeElement.getSimpleName().toString() + "Updater";
        } else {
            return "Base" + typeElement.getSimpleName().toString() + "Updater";
        }
    }

    private String defaultPackageName() {
        return typeElement.getEnclosingElement().toString().replace(".domain.", ".base.domain.");
    }

    private void readFromEnableGenForEntity(EnableGenForEntity annotation) {
        this.packageName = defaultPackageName();
        this.className = buildClassName(annotation.useUpdaterDirect());
    }

    private void readFromEnableGenForAggregate(EnableGenForAggregate annotation) {
        this.packageName = defaultPackageName();
        this.className = buildClassName(annotation.useUpdaterDirect());

    }

    private void readFromGenUpdate(GenUpdater genUpdater) {
        this.packageName = typeElement.getEnclosingElement().toString();
        this.className = buildClassName(genUpdater.useDirect());
        if (StringUtils.isNotEmpty(genUpdater.parent())) {
            this.parentClassName = genUpdater.parent();
        }
    }
}
